const express = require('express');
const cors = require('cors');
const path = require('path');

const app = express();

// 使用统一的数据库连接
const db = require('./db');

// 中间件配置
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));
// 增加请求体大小限制，解决PayloadTooLargeError
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
  next();
});

// 基础路由
app.get('/', (req, res) => {
  res.json({ 
    message: 'API Server is running!', 
    status: 'success',
    timestamp: new Date().toISOString()
  });
});

// 健康检查路由
app.get('/health', (req, res) => {
  res.json({ 
    status: 'healthy',
    database: 'connected',
    timestamp: new Date().toISOString()
  });
});

// 导入路由
const userRouter = require('./router/userRouter');
const textbookRouter = require('./router/textbookRouter');
const orderRouter = require('./router/orderRouter');
const { promiseQuery: query } = require('./db');

app.use('/api/users', userRouter);
app.use('/api/textbooks', textbookRouter);
app.use('/api/orders', orderRouter);

// 分类API路由
app.get('/api/categories', (req, res) => {
  const sql = 'SELECT * FROM categories ORDER BY sort_order ASC';
  
  query(sql)
    .then(result => {
      res.json({
        success: true,
        data: result
      });
    })
    .catch(err => {
      console.error('Database error:', err);
      res.status(500).json({ 
        error: 'Database error',
        message: err.message 
      });
    });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ 
    error: 'Something went wrong!',
    message: err.message 
  });
});



// 404处理
app.use( (req, res, next) => {
  res.status(404).json({ 
    error: 'Route not found',
    path: req.originalUrl 
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
  console.log(`API Base URL: http://localhost:${PORT}`);
});
